import U_backup from "components/new_diy/backup";
import goodSwipe from "components/goods/children/goodSwipe"; //轮播
import GoodsSwiper from "components/goods/children/goods_swiper"; //轮播(新)
import floatOrder from "components/goods/children/float_order"; // 订单飘窗
import priceTitleRepertorySales from "components/goods/children/priceTitleRepertorySales"; //标题。价格
import selfParameterServicetag from "components/goods/children/selfParameterServicetag"; //商品挂件列表
import invitationAndLive from "components/goods/children/plugin/invitationAndLive"; //微贴和直播
import cComment from "components/goods/children/comment"; // 评论
import cCommentlist from "components/goods/children/commentList";
import guessLike from "components/goods/children/guessLike"; //猜你喜欢
import relation from "components/goods/children/relation";
import cservicePopup from "./children/plugin/cservicePopup";

var goods_id = "";
export default {
  props: ["goods_id", "goods_type", "parent_showBigImg", "goods_info", "is_room", "wx_video_link"],
  data() {
    return {
      showGood: false, //页面显示
      imgStart: 0,
      showBigImg: false,
      child_showBigImg: false,
      bigImages: [], //商品详情富文本图片预览
      service_QRcode: "",
      service_mobile: "",
      //live more
      isLoadMore: true,
      live_page: 1,
      total_page: 0,
      showMoreLive: false,
      recordsList: [], //直播间列表
      min_micro: [], //微社区帖子数组
      tabList: [], //微贴和直播
      // 初始评论页数
      commentPage: 1,
      // 是否有更多评论
      noMoreComment: false,
      //是否是o2o
      goodTop: false,
      goodsInfo: {}, //get_goods数据
      goods_plugin: {}, // 插件的数据
      courseId:"", //小节id
      sectionId:"",//章节ID
      videoId:"",

      popStock: 0,
      goodsCount: 1,

      favorite: false,
      isGoods: false,
      cservice: "",
      //商品详情
      third_content: [],

      //底部margin值开关
      isMarginBottom: false,

      //是否租赁商品
      isRent: false,
      isRight: false,

      //购物车id 门店拼团
      card_id: 0,

      // showComment: false,
      commentLimit: [], //评论组件，设置最新5条评论
      totalComment: "", //总评论数
      is_show_default_praise: 0, // 是否显示 默认好评已隐藏
      favorable_rate: "100%", //好评率
      goodDetail: {},  //猜你喜欢和详情数据

      timer: null, //throttleFn方法节流，减少性能开支
      // 一口价的数据
      hasActivity: false,
      // 应用市场
      prdocut_market: {},

      isShow_brand: true, // 品牌介绍
      stepConfig: {}, //组件goodStep配置信息

      btnFlag: false, //显示回到顶部
      btnData: {
        button_size: 40,
        over_top: 500,
        position_location: "right",
        icon_url: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/icon-fontclass-zhiding.png"
      },
      // 海报按钮
      btnData2: {
        button_size: 40,
        over_top: 450,
        position_location: "right",
        icon_url: "https://mini-app-img-1251768088.cos.ap-guangzhou.myqcloud.com/bc_eweima.png"
      },

      isFavoriteIcon: false, //是否显示收藏
      showParameter: false, //商品参数展示
      is_member_enter:true,
      knowledgeList: [],
      setShareInfo:{},//分享信息
      contenVideoPlayInd:null,

      activeChapter: [''],//课程目录
      show1: false, //客服弹窗显示
    };
  },
  activated() {
    window.postShareInfo = this.postShareInfo;//Vue的方法给原生cps调用，则需要把方法挂在Window下面
    this.initPages(); //页面初始化配置
    if (this.fun.getTyep() == 7 || this.fun.isCPS()) {
      this.appSharesinit();
    }
  },
  mounted() {
    window.postShareInfo = this.postShareInfo;//Vue的方法给原生cps调用，则需要把方法挂在Window下面
    this.initPages(); //页面初始化配置
    if (this.fun.getTyep() == 7 || this.fun.isCPS()) {
      this.appSharesinit();
    }
  },
  watch: {
    parent_showBigImg(newValue){
      if(!newValue) {
        this.child_showBigImg = false;
      }
    }
  },
  deactivated() {
    window.postShareInfo = null;
  },
  computed: {
    showComment() {
      return this.$store.state.isShomegGoodComment;
    }
  },
  methods: {
    postShareInfo(params) {
      //params: 原生调用Vue时传值（params）给Vue
      let setShareInfo = this.setShareInfo;
      return setShareInfo; //回调给原生，解决cps app顶部导航分享信息缺失
    },
    initPages() {
      this.is_member_enter = this.goods_info.get_goods && this.goods_info.get_goods.is_member_enter == 1?true:false;
      this.initComponents();
      this.isFavoriteIcon = true;
    },

    deactivatedShowGood() {
      this.showGood = false;
    },
    initComponents() {
      this.posterShow = false;

      //门店购物车id
      this.card_id = this.$route.params.cartId;
      goods_id = this.$route.params.id;

      //初始化客服参数
      this.initCservice("");
      //商品详情 初始化参数
      this.initData();

      // 处理data的数据
      this.getGoodsPage(this.goods_info);

      if (this.is_room == 1) {
        this.getLiveList();
      }

    },
    //初始化客服参数
    initCservice(newCservice, QRcode, mobile) {
      if (!this.fun.isTextEmpty(newCservice)) {
        this.cservice = newCservice;
        if (!this.fun.isTextEmpty(QRcode)) {
          this.service_QRcode = QRcode;
        }
        if (!this.fun.isTextEmpty(mobile)) {
          this.service_mobile = mobile;
        }
      }
    },
    //初始化商品详情参数
    initData() {
      this.showGood = false;
      //初始化一下参数
      this.showBigImg = false;
      this.$emit('setShowBigImg',this.showBigImg);
      this.goodsInfo = {};
      this.goods_plugin = {};
      this.isGoods = false;
      this.isGoodsLove = false;
      this.isMarginBottom = false;

      this.isRent = false;

      this.commentPage = 1; //由于首次进来执行getCommentData后该参数已经变为2，所以在每次进入需要先初始化这个参数为1，否则会获取不到数据

      this.commentLimit = [];
      this.goodDetail = {};
      this.timer = null;
      // this.showComment = false;
      this.recordsList = [];
      this.min_micro = [];
      this.tabList = [];
      this.prdocut_market = {};

      this.service_mobile = "";
      this.service_QRcode = "";
      this.cservice = "";
      this.firstActivityCon = "";

      this.firstActivityCon = "";
      this.third_content = [];

      this.isAddCart = false;

      this.posterImg = null;
      this.plugin_setting = localStorage.getItem("plugin_setting") ? JSON.parse(localStorage.getItem("plugin_setting")) : "";
    },

    getGoodsPage(data) {
      // data全部数据
      this.getData(data.get_goods);
      // 数据更改plugin
      this.goods_plugin = data.plugin || {};
      this.courseId = this.goods_plugin?.course_supply?.chapter[0]?.course_id;
      this.activeChapter[0] = this.goods_plugin?.course_supply?.chapter[0]?.chapter_id;
      this.sectionId = this.goods_plugin?.course_supply?.chapter[0]?.section[0].section_id;
      this.videoId = this.goods_plugin?.course_supply?.chapter[0]?.chapter_id;

      if (data.customer_service) {
        // 客服
        this.service_QRcode = data.customer_service.service_QRcode;
        this.service_mobile = data.customer_service.service_mobile;
        this.cservice = data.customer_service.cservice;
      }


      if (data.is_favorite) {
        this.favorite = data.is_favorite.status == 1 ? true : false;
      }

      if (this.goods_info.plugin && this.goods_info.plugin.micro_communities) {
        let num_list = [];
        for(let i=0;i<this.goods_info.plugin.micro_communities.list.length; i++) {
          num_list.push(this.goods_info.plugin.micro_communities.list[i].has_many_image.length);
        }

        //计算最长的图片数组长度   不断递归整合到this.min_micro
        let maxLength = Math.max(...num_list);
        let index = 0;

        this.handleMicro(index, maxLength - 1);

        // this.min_micro再重新分成6张一组
        let list = [];
        for(let i=0;i<this.min_micro.length;) {
          list.push(this.min_micro.slice(i, i + 6));
          i += 6;
        }
        this.min_micro = list;
        if(this.min_micro.length > 0) {
          this.tabList.push({id: 1,name: '关联微贴'});
        }
      }
      if(this.goods_info.plugin && this.goods_info.plugin.project_template) {
        this.knowledgeList = this.goods_info.plugin.project_template.list;//供应链知识库
        this.tabList.push({id: 3,name: '知识库'});
      }

      this.$nextTick(()=>{
        this.showGood = true;
      });
    },
    handleMicro(index, maxLength) {
      // 处理微社区帖子的图片数据
      let img_list = [];
      for(let i=0;i<this.goods_info.plugin.micro_communities.list.length; i++) {
        if(this.goods_info.plugin.micro_communities.list[i].has_many_image && this.goods_info.plugin.micro_communities.list[i].has_many_image[index]) {
          img_list.push(this.goods_info.plugin.micro_communities.list[i].has_many_image[index]);
        }
      }
      this.min_micro.push(...img_list);
      if(index < maxLength && this.min_micro.length < 12) {
        index++;
        this.handleMicro(index, maxLength);
      }
    },
    //处理get_goods数据
    getData(data) {
      this.goodsInfo = data;
      this.getDetailData();

      this.fun.wxShare(
        "",
        { mid: this.fun.getKeyByMid(), goods_id: goods_id },
        {
          title: this.goodsInfo.has_one_share && this.goodsInfo.has_one_share.share_title ? this.goodsInfo.has_one_share.share_title : this.goodsInfo.title,
          imgUrl: this.goodsInfo.has_one_share && this.goodsInfo.has_one_share.share_thumb ? this.goodsInfo.has_one_share.share_thumb : this.goodsInfo.thumb,
          description: this.goodsInfo.has_one_share && this.goodsInfo.has_one_share.share_desc ? this.goodsInfo.has_one_share.share_desc : ""
        },
        data => {
          if (!this.fun.isTextEmpty(data.shop && data.shop.shop)) {
            this.initCservice(data.shop.shop.cservice); //客服重新赋值
          }
        }
      );
      if (data.comment) {
        this.commentLimit = data.comment.data;
        this.totalComment = data.comment.total_summary ? data.comment.total_summary : 0;
      } else if (data.get_comment) {
        this.commentLimit = data.get_comment.data;
        this.totalComment = data.get_comment.total_summary ? data.get_comment.total_summary : 0;
        this.is_show_default_praise = data.get_comment.is_show_good_reputation_text;
      }

      if (this.goodsInfo.show_push) {
        // 猜你喜欢
        let list = [];
        for(let i=0;i<this.goodsInfo.show_push.length;) {
          list.push(this.goodsInfo.show_push.slice(i, i + 6));
          i += 6;
        }
        this.goodDetail.show_push = list;
      }

      this.favorable_rate = data.favorable_rate;
      this.isGoods = true;

      try {
        wx.miniProgram && wx.miniProgram.postMessage({
          data: { goods_title: this.goodsInfo.title }
        });
      } catch (error) {
        console.log('wx.miniProgram：：：error',error);
      }

      this.isMarginBottom = this.fun.isTextEmpty(data.show_push) ? false : true;
    },
    getDetailData(index, tag) {
      // 商品详情处理
      if (this.goodsInfo.content) {
        let str = this.goodsInfo.content.replace(/src=\"http:/gi, 'src="https:');
        this.goodDetail.content = str;
      }
      this.bigImages = this.getImgSrc(this.goodsInfo.content);
      this.$nextTick(()=>{
        if(this.goodsInfo.content && document.getElementById("goods_content")){
          let contenArr = document.getElementById("goods_content").getElementsByTagName('video');
          this.pauseContenVideo(contenArr)
        }
      })
    },
    pauseContenVideo(contenArr){
      for(let i = 0;i<contenArr.length;i++){
        if(this.contenVideoPlayInd == null){
          contenArr[i].addEventListener('play',(e)=>{
            this.contenVideoPlayInd = i;
            // 第一次赋值
            this.pauseContenVideo(contenArr);
          })
        }else{
          if(i != this.contenVideoPlayInd){
            contenArr[i].pause();
          }
        }

      }
    },

    getLiveList(more) {
      if (!this.isLoadMore) {
        return;
      }
      this.isLoadMore = false; // 防止多次请求分页数据
      if (more && this.live_page >= this.total_page) {
        this.showMoreLive = false;
        console.log("没有更多直播间数据！");
      } else {
        this.live_page = more ? this.live_page + 1 : 1;
        $http
          .post("goods.goods.get-room", { goods_id: this.$route.params.id, page: this.live_page }, "")
          .then(response => {
            if (response.result === 1) {
              this.isLoadMore = true;
              this.total_page = response.data.last_page;
              if (!this.total_page) {
                this.total_page = 0;
              }
              if (!more && this.total_page >= 2) {
                this.showMoreLive = true;
              }
              let list = [];
              for(let i=0;i<response.data.data.length;) {
                list.push(response.data.data.slice(i, i + 2));
                i += 2;
              }
              this.recordsList = [...this.recordsList, ...list];
              if(this.recordsList.length > 0) {
                this.tabList.push({id: 2,name: '直播间'});
              }

            } else {
              this.$toast(response.msg);
            }
          });
      }
    },

    FromTo(data) {
      this.$router.push(this.fun.getUrl("goodsComment",{gid:goods_id,istype:'comment'}));
    },

    CloseComment() {
      this.$store.commit("setShowComment", false);
    },
    //self(已选规格)的方法点击显示选择规格
    contorBuyNow_goodTap(){},

    setShowBigImg(data) {
      this.child_showBigImg = data;
      this.$emit('setShowBigImg',data);
    },

    // 处理富文本图片
    handleHtml($event) {
      if ($event.target) {
        if ($event.target.nodeName == "IMG" && $event.target.parentElement.nodeName !== "A") {
          for (let i = 0; i < this.bigImages.length; i++) {
            // 编程式
            if ($event.target.currentSrc.indexOf(this.bigImages[i]) > -1) {
              this.imgStart = i;
              this.showBigImg = true;
              this.$emit('setShowBigImg',this.showBigImg);
              return;
            }
          }
        }
      }
    },
    getImgSrc(richtext) {
      let imgList = [];
      richtext.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/g, (match, capture) => {
        imgList.push(capture);
      });
      return imgList;
    },
    // 收藏
    onFavorite() {
      let isFavorite = this.favorite;
      let url = isFavorite ? "member.member-favorite.destroy" : "member.member-favorite.store";
      $http.get(url, { goods_id: goods_id }, ".").then(
        response => {
          if (response.result == 1) {
            this.favorite = !isFavorite;
            Toast(`${isFavorite ? "取消收藏" : "收藏成功"}`);
          }
        },
        response => {
          console.log(response);
        }
      );
    },
    changeFavorite(e) {
      this.favorite = e;
    },
    postShow() {
      // 显示海报
      this.$nextTick(()=> {
        this.$refs.priceTitleRepertorySales.postShow();
      });
    },
    //APP分享
    shareWeixin() {
      //不是微信端 不访问
      if (this.fun.getTyep() == 5) {
        return;
      } else if (this.fun.getTyep() == 7 || this.fun.isCPS()) {
        this.shareByApp(this.setShareInfo);
        return;
      }
      this.$dialog.alert({ message: "请点击右上角微信分享" });
    },
    appSharesinit() {
      // app获取分享数据中的data.shop.shop.name
      $http.post("member.member.wxJsSdkConfig", { url: document.location.href },'.').then(
        response => {
          if (response.result == 1) {
            this.appShare(response.data);
          }
        },
        response => {
          console.log(response);
        }
      );
    },
    //app分享设置
    appShare(data) {
      let uid = window.localStorage.getItem("uid");
      let _title,
        _imgUrl,
        _desc = "";
      let _link = document.location.href + "&share_tag=2";
      _link = this.fun.isMid(_link, uid);
      try {
        _title = this.fun.isTextEmpty(this.goodsInfo.has_one_share.share_title) ? this.goodsInfo.title : this.goodsInfo.has_one_share.share_title;
        _imgUrl = this.fun.isTextEmpty(this.goodsInfo.has_one_share.share_thumb) ? this.goodsInfo.thumb : this.goodsInfo.has_one_share.share_thumb;
        _desc = this.fun.isTextEmpty(this.goodsInfo.has_one_share.share_desc) ? (data && data.shop ? data.shop.shop.name:'') : this.goodsInfo.has_one_share.share_desc;

      }catch (e) {
        _title = this.goodsInfo.title;
        _imgUrl = this.goodsInfo.thumb;
        _desc = this.goodsInfo.title;
      }


      let json = {
        title: _title, // 分享标题
        desc: _desc, // 分享描述
        link: `${this.fun.getSiteRoot()}/addons/yun_shop/?menu#/${window.location.href.match(/#\/(\S*)\?/)[1]}?i=${this.fun.getKeyByI()}&mid=${uid}`, // 分享链接
        imgUrl: _imgUrl // 分享图标
      };
      this.setShareInfo = json;

    },
    shareByApp(json){
      if (this.fun.isCPS()) {
        if (this.fun.isIosOrAndroid() === "ios") {
          shareByH5IOS({ body: "shareByH5IOS", json: JSON.stringify(json) });
        } else {
          shareByH5Android(JSON.stringify(json));
        }
      } else {
        YDB.Share(json.title, json.desc, json.imgUrl, json.link, "Sharesback");
      }
    },

    // 跳转
    goto() {
      if (this.fun.isCPS()) {
        if (this.fun.isIosOrAndroid() === "ios") {
          routeBackUrlIOS({ body: "routeBackUrlIOS" });
        } else {
          routeBackUrlAndroid();
        }
        return;
      }
      if (window.history.length <= 1) {
        this.$router.push(this.fun.getUrl("home", {}));
      } else {
        this.$router.go(-1);
      }
    },
    gotoUrl(name, params = {},query={}) {
      this.$router.push(this.fun.getUrl(name, params,query));
    },
    //品牌跳转
    toBrandDetail(val) {
      this.$router.push(this.fun.getUrl("GoodsBrand", { id: val }));
    },
    // 群活码跳转
    toGroupCode() {
      if(this.goods_plugin.group_code.jump_mode === 'home') {
        this.$router.push(this.fun.getUrl("groupCode"));
      }else if(this.goods_plugin.group_code.code_url){
        window.location.href = this.goods_plugin.group_code.code_url;
      }
    },
    clickChat() {
      if (window.isMiniprogram) {
        this.fun.gotoMiniAppCs();
      } else {
        let setServicePlugin = this.fun.isTextEmpty(this.service_mobile) && this.fun.isTextEmpty(this.service_QRcode);
        if (this.fun.isTextEmpty(this.cservice) && setServicePlugin) {
          return this.$toast("抱歉，暂未设置客服信息");
        }
        if (!this.fun.isTextEmpty(this.cservice) && setServicePlugin) {
          //只设置了客服链接，直接跳转
          if (this.cservice && this.cservice.indexOf("chatWindow") >= 0) {
            window.location.href = this.cservice + "&goods_id=" + this.$route.params.id;
          } else {
            window.location.href = this.cservice;
          }
          return;
        }
        this.show1 = true;
      }
    },
    toOrder(){
      let _json = {
        // orderType: "courseSupply",
        tag: "-2",
        goodsId: this.$route.params.id,
        optionsId: this.goodsInfo.has_many_options[0].id,
        total: 1
      };
      this.$router.push(this.fun.getUrl("goodsorder", {}, _json));
    },
    sectionOn(course,section,index){
      let chapter = this.goods_plugin?.course_supply?.chapter[index];
      console.log(chapter.chapter_id)
      if(section.can_try == 0  && this.goods_plugin.course_supply.is_buy == 0) {
        return this.$toast('请先购买课程');
      }
      this.$router.push(this.fun.getUrl("chapterList", { chapterId: this.goods_plugin.course_supply.id,courseId:course.course_id,sectionId: section.section_id,videoId:chapter.chapter_id}));
    }
  },
  filters: {
    videoSecondTime(second) {
      console.log(second);
      let minute = parseInt(second / 60);
      let secondTime = second % 60;
      if(secondTime != 0 || minute !=0) {
        return `${minute}分${secondTime}秒`;
      }
    }
  },
  components: {
    U_backup,
    goodSwipe,
    floatOrder,
    priceTitleRepertorySales,
    selfParameterServicetag,
    invitationAndLive,
    cComment,
    cCommentlist,
    guessLike,
    GoodsSwiper,
    relation,cservicePopup
  }
};